//
//  SCFilterView.m
//  MSEnglishTeachingTeacher
//
//  Created by Chao Sheng on 2022/8/31.
//

#import "SCFilterView.h"
#import "SCBasicKit.h"

@interface SCFilterView ()<UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic, strong) NSMutableArray *selectedTags;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, copy) void(^scFilterSuccess)(NSArray *selectedStates);

@property (nonatomic, strong) UILabel *titleLabel ;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) UIButton *cancel;
@property (nonatomic, strong) UIButton *sure;

@property (nonatomic, strong) NSArray *pickerDataArray;
@property (nonatomic, assign) NSInteger pickerSelectIndex;


@end

@implementation SCFilterView

- (instancetype)init {
    if (self = [super init]) {
        [self addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }
    return self;
}

- (void)setupToolBar {
    _selectedTags = @[].mutableCopy;
    if (_lateseSelectedStates==nil) {
        for (NSInteger i = 0; i < self.filterTitles.count; i++) {
            [_selectedTags addObject:@0];
        }
    } else {
        
        for (NSInteger i = 0; i < _lateseSelectedStates.count; i++) {
            NSString *state = _lateseSelectedStates[i];
            NSArray *currentStateList = self.filterStates[i];
            NSInteger idx = [currentStateList indexOfObject:state];
            [_selectedTags addObject:@(idx)];
        }
    }
    
    
    _contentView = [UIView new];
    _contentView.layer.masksToBounds = true;
    _contentView.backgroundColor = UIColor.whiteColor;
    [self addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
    }];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    _titleLabel = titleLabel;
    titleLabel.text = @"筛选";
    [_contentView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentView);
        make.top.equalTo(@(sc_w(17)));
    }];
    titleLabel.font = sc_PingFangMediumFont(15);
    
    UIView *line = [[UIView alloc] init];
    _line = line;
    line.backgroundColor = sc_colorHex(0xe1e1e1);
    line.alpha = 0.5;
    [_contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(15);
        make.left.right.equalTo(@0);
        make.height.equalTo(@1);
    }];
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancel = cancel;
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel setTitleColor:sc_colorHex(0x0099ff) forState:UIControlStateNormal];
    [cancel setTitleColor:[sc_colorHex(0x0099ff) colorWithAlphaComponent:0.5]  forState:UIControlStateHighlighted];
    cancel.titleLabel.font = sc_PingFangRegularFont(15);
    [cancel addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:cancel];
    [cancel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(sc_w(13)));
        make.centerY.equalTo(titleLabel);
        make.width.equalTo(@(sc_w(30)));
        make.height.equalTo(@(sc_w(40)));
    }];
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    _sure = sure;
    [sure setTitle:@"确定" forState:UIControlStateNormal];
    [sure setTitleColor:sc_colorHex(0x0099ff) forState:UIControlStateNormal];
    [sure setTitleColor:[sc_colorHex(0x0099ff) colorWithAlphaComponent:0.5]  forState:UIControlStateHighlighted];
    sure.titleLabel.font = sc_PingFangRegularFont(15);
    [sure addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:sure];
    [sure mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(sc_w(-13)));
        make.centerY.equalTo(titleLabel);
        make.width.equalTo(@(sc_w(30)));
        make.height.equalTo(@(sc_w(40)));
    }];
}

- (void)setupUI {
    
    [self setupToolBar];
    
    UIView *last = nil;
    for (NSInteger i = 0; i < self.filterTitles.count; i++) {
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = sc_PingFangMediumFont(14);
        titleLabel.text = self.filterTitles[i];
        [_contentView addSubview:titleLabel];

        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(sc_w(17)));
            if (i==0) {
                make.top.equalTo(self.contentView).offset(sc_w(60));
            } else {
                make.top.equalTo(last.mas_bottom).offset(sc_w(20));
            }
            make.height.equalTo(@(sc_w(17)));
        }];
        NSInteger selectedIndex = ((NSNumber*)self.selectedTags[i]).integerValue;
        NSArray *currentfiltreNames = self.filterNames[i];
        UIButton *lastBtn = nil;
        for (NSInteger j = 0; j < currentfiltreNames.count; j++) {
            UIButton *nameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            nameBtn.tag = (i+1) * 1000 + j;
            nameBtn.layer.cornerRadius = 4;
            nameBtn.layer.masksToBounds = YES;
            [nameBtn setTitle:currentfiltreNames[j] forState:UIControlStateNormal];
            [nameBtn setTitleColor:sc_colorHex(0x333333) forState:UIControlStateNormal];
            nameBtn.titleLabel.font = sc_PingFangRegularFont(14);
            nameBtn.backgroundColor = sc_colorHex(0xf9f9f9);
            if (j == selectedIndex) {
                nameBtn.backgroundColor = [sc_colorHex(0x0099ff) colorWithAlphaComponent:0.2];
                [nameBtn setTitleColor:sc_colorHex(0x0099ff) forState:UIControlStateNormal];
            }
            [nameBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
            
            [_contentView addSubview:nameBtn];
            [nameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                if (j % 3 == 0) {
                    make.left.equalTo(@(sc_w(17)));
                    if (j == 0) {
                        make.top.equalTo(titleLabel.mas_bottom).offset(sc_w(12));
                    } else {
                        make.top.equalTo(lastBtn.mas_bottom).offset(sc_w(12));
                    }
                } else {
                    make.left.equalTo(lastBtn.mas_right).offset(sc_w(12));
                    make.top.equalTo(lastBtn);
                }
                make.width.equalTo(@(sc_w(104)));
                make.height.equalTo(@(sc_w(36)));
            }];
            lastBtn = nameBtn;
        }
        
        last = lastBtn;
    }
}

- (void)setupCustomLayoutStyleUI {
    [self setupToolBar];
    
    UIView *last = nil;
    for (NSInteger i = 0; i < self.filterTitles.count; i++) {
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = sc_PingFangMediumFont(14);
        titleLabel.text = self.filterTitles[i];
        [_contentView addSubview:titleLabel];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(sc_w(17)));
            if (i==0) {
                make.top.equalTo(self.contentView).offset(sc_w(60));
            } else {
                make.top.equalTo(last.mas_bottom).offset(sc_w(20));
            }
            make.height.equalTo(@(sc_w(17)));
        }];
        NSInteger selectedIndex = ((NSNumber*)self.selectedTags[i]).integerValue;
        NSArray *currentfiltreNames = self.filterNames[i];
        SCFilterLayoutStyle style = (SCFilterLayoutStyle)[self.filterStyles[i] intValue];
        switch (style) {
            case SCFilterLayoutStyleNormal: case SCFilterLayoutStyleBisect:{
                NSInteger rowCount = style == SCFilterLayoutStyleNormal ? 3 : 2;
                CGFloat itemW = style == SCFilterLayoutStyleNormal ? sc_w(104) : sc_w(167);
                
                UIButton *lastBtn = nil;
                for (NSInteger j = 0; j < currentfiltreNames.count; j++) {
                    UIButton *nameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    nameBtn.tag = (i+1) * 1000 + j;
                    nameBtn.layer.cornerRadius = 4;
                    nameBtn.layer.masksToBounds = YES;
                    [nameBtn setTitle:currentfiltreNames[j] forState:UIControlStateNormal];
                    [nameBtn setTitleColor:sc_colorHex(0x333333) forState:UIControlStateNormal];
                    nameBtn.titleLabel.font = sc_PingFangRegularFont(14);
                    nameBtn.backgroundColor = sc_colorHex(0xf9f9f9);
                    if (j == selectedIndex) {
                        nameBtn.backgroundColor = [sc_colorHex(0x0099ff) colorWithAlphaComponent:0.2];
                        [nameBtn setTitleColor:sc_colorHex(0x0099ff) forState:UIControlStateNormal];
                    }
                    [nameBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
                    
                    [_contentView addSubview:nameBtn];
                    [nameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                        if (j % rowCount == 0) {
                            make.left.equalTo(@(sc_w(17)));
                            if (j == 0) {
                                make.top.equalTo(titleLabel.mas_bottom).offset(sc_w(12));
                            } else {
                                make.top.equalTo(lastBtn.mas_bottom).offset(sc_w(12));
                            }
                        } else {
                            make.left.equalTo(lastBtn.mas_right).offset(sc_w(12));
                            make.top.equalTo(lastBtn);
                        }
                        make.width.equalTo(@(itemW));
                        make.height.equalTo(@(sc_w(36)));
                    }];
                    lastBtn = nameBtn;
                }
                last = lastBtn;
                
            }
                break;

            case SCFilterLayoutStylePicker:{
                self.pickerDataArray = currentfiltreNames;
                self.pickerSelectIndex = selectedIndex;
                UIPickerView *picker = [[UIPickerView alloc] init];
                picker.delegate = self;
                picker.dataSource = self;
                [_contentView addSubview:picker];
                [picker mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(titleLabel.mas_bottom).offset(sc_w(12));
                    make.left.right.equalTo(@0);
                    make.height.equalTo(@(sc_w(140)));
                    make.height.equalTo(@(140));
                }];
                [picker selectRow:self.pickerSelectIndex inComponent:0 animated:YES];
                
                if (@available(iOS 14.0, *)) {
                    UIView *line1 = [[UIView alloc] init];
                    line1.backgroundColor = sc_rgb(225, 225, 225);
                    line1.alpha = 0.5;
                    [picker addSubview:line1];
                    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(@10);
                        make.right.equalTo(@-10);
                        make.height.equalTo(@1);
                        make.top.equalTo(@((sc_w(140)-52)/2-5));
                    }];
                    
                    UIView *line2 = [[UIView alloc] init];
                    line2.backgroundColor = sc_rgb(225, 225, 225);
                    line2.alpha = 0.5;
                    [picker addSubview:line2];
                    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(@10);
                        make.right.equalTo(@-10);
                        make.height.equalTo(@1);
                        make.bottom.equalTo(@(-(sc_w(140)-52)/2+5));
                    }];
                }

                last = picker;
            }
                break;
                
            default:
                break;
        }
        
    }
}

#pragma mark - picker datasource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.pickerDataArray.count;
}

#pragma mark - picker delegate
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return sc_screen_width;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 50;
}

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *title = [self.pickerDataArray[row] stringByRemovingPercentEncoding];
    
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    self.pickerSelectIndex = row;
    
    NSInteger index = 0;
    for(NSInteger i = 0; i < self.filterStyles.count;i++) {
        SCFilterLayoutStyle style = (SCFilterLayoutStyle)[self.filterStyles[i] intValue];
        if(style == SCFilterLayoutStylePicker) {
            index = i;
        }
    }
    [self.selectedTags replaceObjectAtIndex:index withObject:@(self.pickerSelectIndex)];
//    NSLog(@"%@",self.selectedTags);
    [pickerView reloadAllComponents];
    
}

/// 设置picker显示的样式
- (UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    // 设置分割线的颜色
    if (@available(iOS 14.0, *)) {
        if(pickerView.subviews.count == 2) {
            ((UIView *)[pickerView.subviews objectAtIndex:1]).backgroundColor = UIColor.clearColor;
        }
    }else{
        if(pickerView.subviews.count > 2) {
            ((UIView *)[pickerView.subviews objectAtIndex:1]).backgroundColor = sc_rgb(225, 225, 225);
            ((UIView *)[pickerView.subviews objectAtIndex:2]).backgroundColor = sc_rgb(225, 225, 225);
        }
    }
    UILabel *label = (UILabel *)view;
    if (!label) {
        label = [[UILabel alloc]init];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = sc_PingFangRegularFont(15);
        label.textColor = sc_rgb(153, 153, 153);
        // 字体自适应属性
        label.adjustsFontSizeToFitWidth = YES;
        // 自适应最小字体缩放比例
        label.minimumScaleFactor = 0.5f;
    }
    
    NSString *text = self.pickerDataArray[row];
    if(row == self.pickerSelectIndex) {
        NSMutableAttributedString *muattr = [[NSMutableAttributedString alloc] initWithString:text];
        [muattr addAttributes:@{NSFontAttributeName:sc_PingFangMediumFont(16),NSForegroundColorAttributeName:sc_rgb(0, 153, 255)} range:NSMakeRange(0, text.length)];
        label.attributedText = muattr;
    } else {
        label.text = text;
    }
    
    return label;
}

#pragma mark - 事件
- (void)sureAction {
    
    NSMutableArray *states = @[].mutableCopy;
    for (NSInteger i = 0; i < self.selectedTags.count; i++) {
        NSInteger index = ((NSNumber*)self.selectedTags[i]).integerValue;
        NSArray *currentStates = self.filterStates[i];
        [states addObject:[NSString stringWithFormat:@"%@",currentStates[index]]];
    }
    
    if (self.scFilterSuccess) {
        self.scFilterSuccess(states);
    }
    
    [self hide];
}

- (void)cancelAction {
    [self hide];
}

- (void)selectAction:(UIButton*)sender {
    NSInteger index = sender.tag / 1000 ;
    NSInteger selectedTag = ((NSNumber*)self.selectedTags[index-1]).integerValue;

    UIButton *lastSelectedBtn = [self.contentView viewWithTag:(index * 1000 + selectedTag)];
    [lastSelectedBtn setTitleColor:sc_colorHex(0x333333) forState:UIControlStateNormal];
    lastSelectedBtn.backgroundColor = sc_colorHex(0xf9f9f9);
    
    sender.backgroundColor = [sc_colorHex(0x0099ff) colorWithAlphaComponent:0.2];
    [sender setTitleColor:sc_colorHex(0x0099ff) forState:UIControlStateNormal];

    NSInteger currentTag = sender.tag - index * 1000;
    [self.selectedTags replaceObjectAtIndex:index-1 withObject:@(currentTag)];
    
//    NSLog(@"%@",self.selectedTags);
}

- (void)showFilterSuccess:(void (^)(NSArray * _Nonnull))success {
    
    self.scFilterSuccess = success;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
    if(self.filterStyles) {
        [self setupCustomLayoutStyleUI];
    } else {
        [self setupUI];
    }
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    
    NSInteger count = 0;
    for (NSInteger i = 0; i < self.filterTitles.count; i++) {
        NSArray *currentfiltreNames = self.filterNames[i];
        NSInteger index = currentfiltreNames.count/3 + ((currentfiltreNames.count % 3 == 0) ? 0: 1);
        count = count + index + 1;
    }
    CGFloat height = sc_w(48) * count + sc_w(100);
    
    if(self.filterStyles) { ///自定义筛选内容样式时使用
        height = sc_w(100);
        for (NSInteger i = 0; i < self.filterTitles.count; i++) {
            SCFilterLayoutStyle style = (SCFilterLayoutStyle)[self.filterStyles[i] intValue];
            if(style == SCFilterLayoutStylePicker) {
                height = height + sc_w(140) + sc_w(48);
            } else if (style == SCFilterLayoutStyleNormal) {
                NSArray *currentfiltreNames = self.filterNames[i];
                NSInteger index = currentfiltreNames.count/3 + ((currentfiltreNames.count % 3 == 0) ? 0: 1);
                height = height + (index + 1) * sc_w(48);
            } else {
                NSArray *currentfiltreNames = self.filterNames[i];
                NSInteger index = currentfiltreNames.count/2 + ((currentfiltreNames.count % 2 == 0) ? 0: 1);
                height = height + (index + 1) * sc_w(48);
            }
        }
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@(height));
            make.height.equalTo(@(height));
        }];

        [self.contentView sc_roundingCorner:UIRectCornerTopLeft | UIRectCornerTopRight inRectSize:CGSizeMake( sc_screen_width, height) cornerRadius:sc_w(8)];
        
        [UIView animateWithDuration:0.3 animations:^{
            [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(@(sc_w(0)));
            }];
            [self layoutIfNeeded];
            
        } completion:^(BOOL finished) {
                
        }];
    });
}

- (void)hide {
    [UIView animateWithDuration:0.3 animations:^{
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@(sc_screen_width));
        }];
        [self layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
